<?php

namespace DreamCat\FrameCore;

use Components\Utils\Funcs\ArrayFunc;
use DreamCat\FrameInterface\ConfigReader;

/**
 * 配置读取器
 * @author vijay
 */
class ConfigReaderImpl implements ConfigReader
{
    /** @var string 项目根目录 */
    private $rootDir;
    /** @var array 配置内容 */
    private $configs;

    /**
     * ConfigReader constructor.
     * @param string $rootDir 项目根目录
     */
    public function __construct(string $rootDir)
    {
        $this->rootDir = $rootDir;
        $this->configs = $this->readConfigFromFile();
    }

    /**
     * 从配置文件中读取配置
     * @return array 配置信息
     */
    protected function readConfigFromFile(): array
    {
        $fileList = $this->getConfigFiles();
        $config = [];
        foreach ($fileList as $fileName) {
            if (!file_exists($fileName)) {
                continue;
            }
            if ($config) {
                /** @noinspection PhpIncludeInspection */
                $config = ArrayFunc::overwriteMerge($config, include $fileName);
            } else {
                /** @noinspection PhpIncludeInspection */
                $config = include $fileName;
            }
        }
        return $config;
    }

    /**
     * 获取配置文件列表，越往后优先级越高
     * @return string[] 文件名列表
     */
    protected function getConfigFiles(): array
    {
        return [
            "{$this->rootDir}/configs/config.php",
            "{$this->rootDir}/cache/configs/config.php",
        ];
    }

    /**
     * 读取配置
     * @param string $path 配置路径
     * @param mixed $defaultValue 不存在的情况下的默认值
     * @return mixed 配置内容
     */
    public function get(string $path, $defaultValue = null)
    {
        return ArrayFunc::getArrayChild($this->configs, $path, $defaultValue);
    }

    /**
     * 获取项目根目录
     * @return string 项目根目录
     */
    public function getRootDir(): string
    {
        return $this->rootDir;
    }
}

# end of file
